package com.fa.controller;

import com.fa.service.CodeGeneratorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayOutputStream;
import java.util.zip.ZipOutputStream;

@RestController
@RequestMapping("/code-generator")
public class CodeGeneratorController {

    @Autowired
    private CodeGeneratorService codeGeneratorService;

    /**
     * 客户端请求生成代码并下载 ZIP 文件
     *
     * @param databaseName 数据库名称
     * @param tableName    表名
     * @return 通过响应流直接下载 ZIP 文件
     */
    @GetMapping("/download")
    public ResponseEntity<byte[]> generateAndDownloadCode(@RequestParam String databaseName, @RequestParam String tableName) {
        try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
             ZipOutputStream zipOutputStream = new ZipOutputStream(byteArrayOutputStream)) {

            // 生成代码并写入 ZIP 输出流
            codeGeneratorService.generateCodeToZipStream(databaseName, tableName, zipOutputStream);

            // 完成压缩并关闭流
            zipOutputStream.finish();

            // 将字节数组返回给客户端
            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + tableName + "-code.zip\"");
            return ResponseEntity.ok()
                    .headers(headers)
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .body(byteArrayOutputStream.toByteArray());

        } catch (Exception e) {
            return ResponseEntity.status(500).body(null);
        }
    }
}
